#include "ConductorParser.h"

#include "PropertyParser.h"
#include "ConductorListParser.h"
#include "QStringParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

ConductorParser::ConductorParser(
    ConductorListParser *&_typeParser
    , QStringParser *&_commentParser
    , PropertyParser *&_propertyParser
):    m_typeParser(_typeParser)
    , m_commentParser(_commentParser)
    , m_propertyParser(_propertyParser)
{

}

bool ConductorParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new Conductor());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("type")))
    {
        data = reader->attributes().value(QStringLiteral("type"));
        if (!m_typeParser->parse(reader, data))
            return false;
        m_result->type = m_typeParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("type: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("comment")))
    {
        data = reader->attributes().value(QStringLiteral("comment"));
        if (!m_commentParser->parse(reader, data))
            return false;
        m_result->commentOptional = Optional<QString>(m_commentParser->result());
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
        if (name == QStringLiteral("Property"))
        {
            if (!m_propertyParser->parse(reader))
                return false;
            auto result = m_propertyParser->result();
            m_result->propertyList.append(result);
        }
        else
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

Conductor *ConductorParser::result()
{
    return m_result.take();
}

}